from django.contrib import admin
from django.urls import resolve
from certificate_manager.models import Cate, Manageship, Department, DepartRestrict, Level
from django.db.models import Q

from django.utils.translation import gettext_lazy as _

class ManageshipInline(admin.TabularInline):
	model = Manageship
	extra = 1

class DepartRestrictInline(admin.TabularInline):
	model = DepartRestrict
	extra = 2

class LevelInline(admin.TabularInline):
	model = Level
	extra = 2

	def get_parent_object_from_request(self, request):
		"""
		Returns the parent object from the request or None.

		Note that this only works for Inlines, because the `parent_model`
		is not available in the regular admin.ModelAdmin as an attribute.
		"""
		resolved = resolve(request.path_info)
		if resolved.kwargs:
		    return self.parent_model.objects.get(pk=resolved.kwargs['object_id'])
		return None

	def formfield_for_foreignkey(self, db_field, request, **kwargs):
		parent = self.get_parent_object_from_request(request)
		if db_field.name == "nested_level":
			kwargs["queryset"] = Level.objects.filter(cate_id=parent)
		return super().formfield_for_foreignkey(db_field, request, **kwargs)


@admin.register(Cate)
class CateAdmin(admin.ModelAdmin):
	fields = ['name', 'nested_cate', 'collect_part', 'collecable']
	list_display = ('pk', 'name', 'collect_part')
	
	inlines = [
		ManageshipInline,
		DepartRestrictInline,
		LevelInline
	]

	def get_form(self, request, obj=None, **kwargs):
		form = super().get_form(request, obj, **kwargs)
		form.base_fields['nested_cate'].queryset = Cate.objects.filter(collecable=False)
		return form

